#include "systemconfig.h"
#include "ui_systemconfig.h"
#include <QMessageBox>
#include "systempreset.h"
#include "shadow.h"
#include "msgbox.h"
#include "log4z.h"
#include "authmanager.h"
#include "frminput2019.h"
#include "userlogger.h"

using namespace zsummer::log4z;

SystemConfig::SystemConfig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SystemConfig)
{
    ui->setupUi(this);
    bdf = BllDataFlow::getInstance();
    sqlHelper = SqlHelper::getInstance();

    //Signals and Slots
    connect(bdf, &BllDataFlow::changeSystemConfigPageIndexSignal, this, &SystemConfig::changeSystemConfigPageIndexSlot);
    connect(ui->lineNewUsernameVerfiy, &QLineEdit::returnPressed,this,&SystemConfig::on_btnChangeUsername_clicked);
    connect(bdf, &BllDataFlow::setWidgetVisibleSignal,this,&SystemConfig::setWidgetVisibleSlot);
    connect(bdf, &BllDataFlow::retranslateUiSignal, this, &SystemConfig::retranslateUiSlot);

    connect(ui->lineOldPW, &QLineEdit::textChanged, this, &SystemConfig::clearPasswordError);
    connect(ui->lineNewPW, &QLineEdit::textChanged, this, &SystemConfig::clearPasswordError);
    connect(ui->lineNewPWVerfiy, &QLineEdit::textChanged, this, &SystemConfig::clearPasswordError);

    map.insert(USERNAME,  ui->btnUsername);
    map.insert(PASSWORD,  ui->btnPassword);
    map.insert(NETWORK,   ui->btnNetwork);
    map.insert(PRINT_SET, ui->btnPrint);
    map.insert(TIME_SET,  ui->btnTime);
    map.insert(LANGUAGE,  ui->btnLanguage);

    initWidget();
}

SystemConfig::~SystemConfig()
{
    delete ui;
}

void SystemConfig::changeSystemConfigPageIndexSlot(int index)
{
    if (index != -1)
    {
        ui->stackedWidget->setCurrentIndex(index);
        ui->stackedWidget->setVisible(true);
    }
    else
    {
        ui->stackedWidget->setVisible(false);
    }
}

void SystemConfig::on_btnUsername_toggled(bool checked)
{
    if (checked)
    {
        bdf->changeSystemConfigPageIndex(SystemConfigIndex::USERNAME);
    }
}

void SystemConfig::on_btnPassword_toggled(bool checked)
{
    if (checked)
    {
        clearPasswordError();
        clearPasswordInput();
        bdf->changeSystemConfigPageIndex(SystemConfigIndex::PASSWORD);
    }
}

void SystemConfig::on_btnNetwork_toggled(bool checked)
{
    if (checked)
    {
        bdf->changeSystemConfigPageIndex(SystemConfigIndex::NETWORK);
    }
}

void SystemConfig::on_btnPrint_toggled(bool checked)
{
    if (checked)
    {
        bdf->changeSystemConfigPageIndex(SystemConfigIndex::PRINT_SET);
    }
}

void SystemConfig::on_btnTime_toggled(bool checked)
{
    if (checked)
    {
        bdf->changeSystemConfigPageIndex(SystemConfigIndex::TIME_SET);
        bdf->setCurrentTime(TimeSetType::SET_TIME);
    }
}

void SystemConfig::on_btnLanguage_toggled(bool checked)
{
    if (checked)
    {
        bdf->changeSystemConfigPageIndex(SystemConfigIndex::LANGUAGE);
    }
}

void SystemConfig::on_btnChangeUsername_clicked()
{
    //Check - not empty
    QString newUsername = ui->lineNewUsername->text().trimmed();
    QString newUsernameVerify = ui->lineNewUsernameVerfiy->text().trimmed();
    if(newUsername.isEmpty() || newUsernameVerify.isEmpty())
    {
        MsgBox::warning(this, QString(tr("Username")),QString(tr("New username empty!")));
        return;
    }

    //Check - 1st and 2nd are the same
    int resComp = newUsernameVerify.compare(newUsername);
    if(0 != resComp)
    {
        MsgBox::warning(this, QString(tr("Username")),QString(tr("Confirm new username error!")));
        return;
    }

    //Check - not same as the current
    resComp = newUsername.compare(currentUsername);
    if(0==resComp)
    {
        MsgBox::warning(this, QString(tr("Username")),QString(tr("New username should be different!")));
        return;
    }

    //Check done
    QString qsQuery = QString("update t_user set name='%1' "
                              "where name = '%2'").arg(newUsername).arg(currentUsername);
    EttaError res = sqlHelper->updateTable(qsQuery);
    if(EttaError::OK == res)
    {
        currentUsername = newUsername;
        bdf->setUserStatusText(currentUsername);
        ui->lineNewUsername->clear();
        ui->lineNewUsernameVerfiy->clear();
        MsgBox::information(this, QString(tr("Username")), QString(tr("Succeed to change Username!")));
    }
    else
    {
        MsgBox::warning(this, QString(tr("Username")), QString(tr("Fail to change Username!")));
    }
}

void SystemConfig::on_lineNewUsername_editingFinished()
{
    QString newUsername = ui->lineNewUsername->text().trimmed();
    int res = newUsername.compare(currentUsername);
    if(0==res)
    {
        MsgBox::warning(this, QString(tr("Username")),QString(tr("New username should be different!")));
    }
}

void SystemConfig::on_btnChangePW_clicked()
{
    clearPasswordError();

    ui->lineOldPW->deselect();
    ui->lineNewPW->deselect();
    ui->lineNewPWVerfiy->deselect();
    frmInput2019::Instance()->hideAndClearFocus();

    QString oldPW = ui->lineOldPW->text().trimmed();
    QString newPW = ui->lineNewPW->text().trimmed();
    QString newPWVerify = ui->lineNewPWVerfiy->text().trimmed();

    EttaError res = sqlHelper->checkLogInfo(currentUsername, oldPW);
    if (EttaError::LOGIN_USER_PW_MISMATCH == res)
    {
        ui->lineOldPW->selectAll();
        ui->lblOldPasswordError->setText(tr("Old password error"));
        return;
    }

    if (!checkPwValid(newPW))
    {
        ui->lineNewPW->selectAll();
        ui->lblNewPasswordError->setText(tr("Passwords does not meet requirements"));
        return;
    }

    if (oldPW == newPW)
    {
        ui->lineNewPW->selectAll();
        ui->lblNewPasswordError->setText(tr("The new password cannot use the previous password"));
        return;
    }

    if (newPW != newPWVerify)
    {
        ui->lineNewPWVerfiy->selectAll();
        ui->lblConfirmError->setText(tr("The passwords entered twice do not match"));
        return;
    }

    //Check done
    QString qsQuery = QString("update t_user set password='%1' where name = '%2'").arg(newPW).arg(currentUsername);
    res = sqlHelper->updateTable(qsQuery);
    if(EttaError::OK == res)
    {
        currentPassword = newPW;
        QString message = QString("%1, %2").arg(tr("Succeed to modify password")).arg(tr("please login again."));
        UserLogger::log(message);
        MsgBox::information(this, tr("Tips"), message);
        clearPasswordInput();
        bdf->changeMainPageIndex(MainPageIndex::LOGIN);
        bdf->logout();
    }
    else
    {
        QString message = tr("Fail to modify password");
        UserLogger::log(message);
        MsgBox::warning(this, tr("PassWord"), message);
    }
}

void SystemConfig::clearPasswordError()
{
    ui->lblOldPasswordError->clear();
    ui->lblNewPasswordError->clear();
    ui->lblConfirmError->clear();
    ui->label_12->hide();
    ui->label_13->hide();
    ui->label_14->hide();
}

void SystemConfig::setWidgetVisibleSlot(int permission)
{
    AuthManager::instance()->showControls(ui->widget, permission);
    int index = AuthManager::instance()->showContainer(ui->widget);
    if (map.contains(index))
    {// 切换到指定页面
        QPushButton *button = map.value(index);
        emit button->toggled(true);
        button->setChecked(true);
    }
    else
    {
        changeSystemConfigPageIndexSlot(-1);
    }
}

void SystemConfig::initWidget()
{
    // 为部分控件添加阴影
    setShadow({ui->pgNetwork,ui->pgPrint,ui->pgTime}, InputType::Line);
    setShadow({ui->widget_6, ui->widget_7, ui->widget_8});
    if (windowWidth >= 1280) {
        ui->btnShowOldPw->setMaximumSize(70,70);
        ui->btnShowNewPw->setMaximumSize(70,70);
        ui->btnShowConfirmPw->setMaximumSize(70,70);
    }

    ui->stackedWidget->setCurrentIndex(1);
    ui->btnUsername->setVisible(false);
    if(gLanguage.toUpper() == "CN")
    {
        ui->btnCh->setChecked(true);
    }
    else if (gLanguage.toUpper() == "EN") {
        ui->btnEn->setChecked(true);
    }

    ui->lineOldPW->setValidator(gPwValidator);
    ui->lineNewPW->setValidator(gPwValidator);
    ui->lineNewPWVerfiy->setValidator(gPwValidator);

    clearPasswordError();
}

void SystemConfig::saveParam()
{
    SystemPreset::instance()->setData(EnumPresetItem::Language, gLanguage);
}

void SystemConfig::clearPasswordInput()
{
    ui->lineOldPW->clear();
    ui->lineNewPW->clear();
    ui->lineNewPWVerfiy->clear();
}

void SystemConfig::retranslate(const QString &lang)
{
    gLanguage = lang;
    qApp->removeTranslator(translator);
    delete translator;
    translator = new QTranslator();
    bool state = translator->load(TranslationFile);
    qApp->installTranslator(translator);
    bdf->retranslateUi();
    saveParam();
    LOGFMTD("load etta_%s.qm state: %d", lang.toLower().toStdString().data(), state);
}

void SystemConfig::on_btnCh_clicked()
{
    UserLogger::log(QString("%1: %2").arg(tr("Switch system language")).arg("中文"));
    retranslate("CN");
}

void SystemConfig::on_btnEn_clicked()
{
    UserLogger::log(QString("%1: %2").arg(tr("Switch system language")).arg("English"));
    retranslate("EN");
}

void SystemConfig::retranslateUiSlot()
{
    ui->retranslateUi(this);
}

void SystemConfig::on_btnShowOldPw_toggled(bool checked)
{
    if(checked)
    {
        ui->btnShowOldPw->setStyleSheet("border:none;border-image:url(:/resources/eye_open.png)");
        ui->lineOldPW->setEchoMode(QLineEdit::Normal);
    }
    else
    {
        ui->btnShowOldPw->setStyleSheet("border:none;border-image:url(:/resources/eye_close.png)");
        ui->lineOldPW->setEchoMode(QLineEdit::Password);
    }
}

void SystemConfig::on_btnShowNewPw_toggled(bool checked)
{
    if(checked)
    {
        ui->btnShowNewPw->setStyleSheet("border:none;border-image:url(:/resources/eye_open.png)");
        ui->lineNewPW->setEchoMode(QLineEdit::Normal);
    }
    else
    {
        ui->btnShowNewPw->setStyleSheet("border:none;border-image:url(:/resources/eye_close.png)");
        ui->lineNewPW->setEchoMode(QLineEdit::Password);
    }
}

void SystemConfig::on_btnShowConfirmPw_toggled(bool checked)
{
    if(checked)
    {
        ui->btnShowConfirmPw->setStyleSheet("border:none;border-image:url(:/resources/eye_open.png)");
        ui->lineNewPWVerfiy->setEchoMode(QLineEdit::Normal);
    }
    else
    {
        ui->btnShowConfirmPw->setStyleSheet("border:none;border-image:url(:/resources/eye_close.png)");
        ui->lineNewPWVerfiy->setEchoMode(QLineEdit::Password);
    }
}

